const express = require("express");
const router = express.Router();
const jwt = require("jsonwebtoken");
const secretKey = "role_id";
const { userModel } = require("../model/user");
const { log } = require("debug");
const { default: axios } = require("axios");

router.get("/weixin/wxLogin/:code", function (req, res, next) {
  let code = req.params.code;
  let token = jwt.sign({ code }, secretKey, { expiresIn: 1000 * 3600 });
  res.send({
    code: 201,
    msg: "登录成功",
    token,
  });
});


router.get("/weixin/auth/getwechatopenid", (req, res) => {
  let JSCODE = req.query.jsCode;
  axios({
    method: "get",

    // NOTE - WJC
    // url: `https://api.weixin.qq.com/sns/jscode2session?appid=wxd51d817f53bfd1c7&secret=68005171af12895f1e91ac5a9fd369e7&js_code=${JSCODE}&grant_type=authorization_code`,
    //NOTE - YLX
    url: `https://api.weixin.qq.com/sns/jscode2session?appid=wxec47edb3a98473b6&secret=27ad7fcc7f6a9c14d7cf8d0ab9a2a2aa&js_code=${JSCODE}&grant_type=authorization_code`,

    //NOTE - CYP
    // url: `https://api.weixin.qq.com/sns/jscode2session?appid=wxec47edb3a98473b6&secret=27ad7fcc7f6a9c14d7cf8d0ab9a2a2aa&js_code=${JSCODE}&grant_type=authorization_code`,
  }).then((infoRes) => {
    res.send({ openid: infoRes.data.openid });
  });
});

router.post("/weixin/auth/updateUser", async (req, res) => {
  let openId = req.body.openId;
  console.log(req.body, 1111111);
  let data;
  const isUser = await userModel.find({ openId }).count();
  console.log(isUser, 222222);
  switch (isUser) {
    case 0:
      data = await userModel.create(req.body);
      break;
    default:
      data = await userModel.find({ openId });
      break;
  }
  res.send({ code: 200, msg: "用户数据更新成功", data: data[0] });
});

router.post("/nomp/login", async (req, res) => {
  let username = req.body.username;
  let password = req.body.password;
  let isUser = await userModel.find({ username }).exec();
  switch (isUser.length) {
    case 1:
      switch (isUser[0].password === password) {
        case true:
          const token = jwt.sign({...isUser[0]}, "keyword", { expiresIn: "60" });
          res.send({
            data: { code: 200, msg: "登录成功", data: isUser[0], token },
          });
          break;
        default:
          res.send({ code: 302, msg: "密码不正确" });
          break;
      }
      break;
    default:
      res.send({ code: 301, msg: "账号未注册" });
      break;
  }
});

module.exports = router;
